package com.galaxy.payment.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QrCodeGenerator {

    /**
     * 生成Base64格式的二维码图片
     * @param content 二维码内容
     * @param width 宽度(像素)
     * @param height 高度(像素)
     * @return base64编码的图片数据(带data:image/png;base64前缀)
     */
    public static String generateBase64QrCode(String content, int width, int height) {
        try {
            // 参数校验
            if (content == null || content.isEmpty()) {
                throw new IllegalArgumentException("二维码内容不能为空");
            }

            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错率
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码格式
            hints.put(EncodeHintType.MARGIN, 1); // 边距

            // 生成二维码矩阵
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            // 转换为图片
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 转换为Base64
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", os);
            byte[] imageBytes = os.toByteArray();

            return "data:image/png;base64," + Base64.encodeBase64String(imageBytes);
        } catch (WriterException | IOException e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }
}
